<?php

namespace Biz\service\activity\project;

use Biz\tools\Mail;
use Encore\Admin\Grid;
use Exception;

trait FieldAuthorizationTrait
{
    public function displayGroupField($auth): bool
    {
        if (is_scalar($auth)) $auth = [$auth];
        foreach ($auth as $mode) {
            if ($mode & 1) return true;
            if ($mode & 2) return true;
        }
        return false;
    }

    public function execForm($mode): bool
    {
        return ($mode & 4);
    }
    public function exportField($mode): bool{
        return ($mode & 4);
    }
    public function displayForm($mode): bool
    {
        return ($mode & 1) || ($mode & 2);
    }

    public function disableForm($form, $mode)
    {
        if (!($mode & 2)) $form->disable();
    }

    public function saveForm($mode): bool
    {
        return ($mode & 2);
    }

    /**
     * @throws Exception
     */
    public function validateEmptyArray($value, $message = '', $isThrow = true): bool
    {
        $rs = !is_array($value) || empty($value);
        if ($rs && $isThrow) throw new Exception($message);
        return !$rs;
    }

    /**
     * @throws Exception
     */
    public function validateNumeric($value, $message = '', $isThrow = true): bool
    {
        $rs = strlen($value) && !is_numeric($value);
        if ($rs && $isThrow) throw new Exception($message);
        return !$rs;
    }

    /**
     * @throws Exception
     */
    public function validatePositiveInt($value, $message = '', $isThrow = true, $includeZero = true): bool
    {
        $newValue = intval($value);
        if ($newValue != $value) {
            if ($isThrow) {
                throw new Exception($message);
            } else {
                return false;
            }
        }
        $rs = $includeZero ? $value < 0 : $value <= 0;
        if ($rs && $isThrow) throw new Exception($message);
        return !$rs;
    }

    public function sendMail($email, $title, $body, $filePath = null, $fileName='', $cc = [])
    {
        $email = array_unique($email);
        Mail::send($email, $title, $body, $filePath, $fileName, $cc);
    }


}